#include "AngleGridItem.h"

#include <QFontDatabase>
#include <QPainter>
#include <QSize>

#include "../IdRootMenu.h"
#include "../vhc/constview4color.h"

#include "../TViewDraw.h"


#include "../../rwidgets/MacroFunOfView.h"

#include "mcore/map/MapObject.h"
#include "mcore/tools/EditWidget.h"
#include "mcore/tools/protactor/ProtactorConst.h"

#include <QPainterPath>
#include <QDebug>
#include <QString>
#include <QPoint>
#include <QFont>

#include <QSvgRenderer>


namespace kepen {
namespace core {

#define Width_MyBtn 48


AngleGridItem::AngleGridItem(QWidget *parent,ProtactorToolView *parentContext,const int *IdArray)
    : QWidget{parent},
    editContext(parentContext),
    isMouseLeftDown(false),
    isWindowDeactivate(false),
    m_nIdTouchedDown(MenuId_None),
    m_nIdMouseOver(MenuId_None)
{


    int nSpace = 0x990002;
    int widthBtn = Width_MyBtn;//(AngleMode_Hor == IdArray[0])?36:Width_MyBtn;
    m_nLengthMenu = 3;
    idMenuArray[0] =IdArray[0];
    idMenuArray[1] = nSpace;
    idMenuArray[2] =IdArray[1];
    cellWidthArr[0] = widthBtn;
    cellWidthArr[1] = WhiteSpace_M & nSpace;
    cellWidthArr[2] = widthBtn;


    int  nGridWidth = widthBtn<<1;


    QSizePolicy sizePoFixed(QSizePolicy::Policy::Fixed, QSizePolicy::Policy::Fixed);
    sizePoFixed.setHorizontalStretch(0);
    sizePoFixed.setVerticalStretch(0);
    sizePoFixed.setHeightForWidth(false);

    setSizePolicy(sizePoFixed);
    setFixedSize(nGridWidth,Height_CELL);

    setMouseTracking(true);
    QObject::installEventFilter(this);
}

AngleGridItem::~AngleGridItem()
{



}

bool AngleGridItem::eventFilter(QObject *watched, QEvent *event)
{
   WindowDeactivate_EventFilter_Only()
}

void AngleGridItem::leaveEvent(QEvent *)
{
    m_nIdMouseOver = MenuId_None;
    repaint();
}


void AngleGridItem::mouseMoveEvent(QMouseEvent *event)
{
    if(false == isMouseLeftDown){
        QPointF point = event->position();
        int nIdMouseOver = m_nIdMouseOver;

        m_nIdMouseOver = getIdOfTouched(point);
        if(nIdMouseOver != m_nIdMouseOver )
        {
            repaint();
        }
    }
}


void AngleGridItem::mousePressEvent(QMouseEvent *event)
{
    Qt::MouseButton btn = event->button();
    if(Qt::MouseButton::LeftButton == btn)
    {
        QPointF point = event->position();

        ptDown = point;
        isMouseLeftDown = true;
        m_nIdTouchedDown = getIdOfTouched(point);

        m_nIdMouseOver = MenuId_None;
        // editContext->repaintToolBar();
        repaint();
    }
}


void AngleGridItem::mouseReleaseEvent(QMouseEvent *event)
{
    int idTouched = m_nIdTouchedDown;
    bool isIgnore =(MenuId_None == idTouched) ||((IS_WhiteSpaceBar(idTouched)));
    bool _isMouseLeftDown = isMouseLeftDown;
    m_nIdTouchedDown = MenuId_None;
    m_nIdMouseOver = MenuId_None;

    isMouseLeftDown = false;

    if(_isMouseLeftDown)
    {
        Qt::MouseButton btn = event->button();
        if (Qt::MouseButton::LeftButton == btn)
        {
            QPointF pointUp = event->position();
            QPointF  ptUp = pointUp - ptDown;

            int x = ptUp.x(),y = ptUp.y();
            bool isClicked = x >-DisTorClicked && x < DisTorClicked && y >-DisTorClicked && y < DisTorClicked;

            if(false == isIgnore && isClicked)
            {
                editContext->onBtnClicked(idTouched);
            }
        }
    }

}


void AngleGridItem::paintEvent(QPaintEvent *)
{

    int widthWindow ,heightWidow;
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing |QPainter::VerticalSubpixelPositioning);

    QSize rectWin = this->size();
    widthWindow  = rectWin.width();
    heightWidow = rectWin.height();

    painter.fillRect(0,0,widthWindow ,heightWidow,Qt::transparent);

    onPaintButtons(&painter);


}




int AngleGridItem::getIdOfTouched(const QPointF &point)
{
    int x0 = qRound(point.x());
    int nRet = MenuId_None;

    int i, numBtns = m_nLengthMenu;
    int left, right;
    int nCellWidth;
    // int _id;

    right =  0;

    for (i = 0; i < numBtns; ++i) {

        left = right;
        nCellWidth = cellWidthArr[i];
        right = left + nCellWidth;
        if (x0 >= left && x0 < right) {
            nRet = idMenuArray[i];
            break;
        }

    }

    return nRet;
}

void AngleGridItem::onPaintButtons(QPainter *painter)
{
    int childWidth = 0,childHeight = Height_CELL;
    int _nID_touchedDown = m_nIdTouchedDown;
    int nIdMouseOver = m_nIdMouseOver;
    bool isEnable ,isChecked,isMouseOver,isTouchedDown,isDeAct = isWindowDeactivate;
    // bool isFocused = hasFocus();
    quint32 boolFlag;
    std::size_t i, numBtns = m_nLengthMenu;
    int left, right;
    int topOfLine = 0;

    int id,sizeTextIcon = 6 + TextSize_Icon_Tool;


    const int * cellWidthPtr = cellWidthArr;
    ProtactorParamData &param = editContext->segmentPicked->mProtaData;




    right =  0;
    for (i = 0; i < numBtns; ++i)
    {
        id = idMenuArray[i];
        left = right;
        childWidth = cellWidthPtr[i];
        right = left + childWidth;

        if (IS_WhiteSpaceBar(id))
            continue;

        isChecked = param.isCheckedBy(id);
        isEnable = param.isEnableBy(id);
        //if(PickMode_Line==id|| IdentifyMode_Point == id)isChecked = true;//test





        isMouseOver = nIdMouseOver == id;
        isTouchedDown = _nID_touchedDown == id;

        boolFlag = isChecked ? BoolFlagChecked : 0;

        if(isDeAct)boolFlag |= BoolFlagDeactivate;

        if(isEnable){
            boolFlag |= BoolFlagEnable;
            if(isMouseOver)boolFlag |= BoolFlagMouseOver;
            if(isTouchedDown)boolFlag |= BoolFlagTouched;
        }







        if(false == ((IS_WhiteSpaceBar(id)) ||  (IS_LabelBar(id)))){

            if(isChecked && false == isDeAct
                && false == isMouseOver
                && false == isTouchedDown)
            {
                QBrush _brushTogBtn(QColor(QRgba64::fromArgb32(Checked_Background)),Qt::SolidPattern);

                painter->fillRect(left, topOfLine, childWidth,childHeight,_brushTogBtn);
            }


            if (isEnable && isMouseOver
                && false == isTouchedDown){

                quint32 nBackColor = isDeAct? 0xffffffffU: (isChecked ?  Checked_Background_Over : Background_BtnOver);

                QBrush brushBackOver(QColor(QRgba64::fromArgb32(nBackColor)),Qt::SolidPattern);


                painter->fillRect(left, topOfLine, childWidth,childHeight,brushBackOver);

                // qDebug().noquote()  <<__FILE__ <<",Line:"<<__LINE__ << "  isDeAct : " << isDeAct <<"  nBackColor   " <<  QString::asprintf("%08X",nBackColor);
            }

            if (isEnable && isTouchedDown){
                quint32 nBackColor = isChecked ?  Checked_Background2_Touched:Background_BtnDown;
                QBrush brushBackDown(QColor(QRgba64::fromArgb32(nBackColor)),Qt::SolidPattern);
                painter->fillRect(left, topOfLine, childWidth,childHeight,brushBackDown);

            }

        }


        if(AnchorPartSegment_Pre == id)
        {
            int cx0, cy0;
            cx0 = left + (childWidth >> 1);
            cy0 = topOfLine + (childHeight >> 1);
            drawPartSegmentPre(painter,cx0, cy0, boolFlag);
        }else if(AnchorPartSegment_Post == id)
        {
            int cx0, cy0;
            cx0 = left + (childWidth >> 1);
            cy0 = topOfLine + (childHeight >> 1);
            drawPartSegmentSub(painter,cx0, cy0, boolFlag);
        }else
        {

            DRAW_ICON_Font(left,topOfLine,sizeTextIcon,id)
        }


        if(isChecked)
            TViewDraw::DrawCheckedTriFlag(painter,left, topOfLine, childWidth,childHeight,boolFlag);

    }
}



void AngleGridItem::drawPartSegmentPre(QPainter* painter,int x,int y, quint32 boolFlag)
{
    int left,right,r = 16,y0 = -1 + y;
    int xArrow = 5 +x,yArrow = 7 +y;
    DefineColorTxtR2();

    qreal thickness = 1.8f ;

    QBrush brushFill(QColor(QRgba64::fromArgb32(focusColor)),Qt::SolidPattern);
    QBrush brushBorder(QColor(QRgba64::fromArgb32(textColor)),Qt::SolidPattern);
    QPen pen(brushBorder,thickness, Qt::SolidLine);


    painter->setBrush(brushFill);
    painter->setPen(pen);
    drawSvgArrow(painter,xArrow,yArrow,boolFlag);
    left = x - r;
    right = x + r;

    painter->drawLine(left,y0,right,y0);


    QBrush brushRed(QColor(QRgba64::fromArgb32(Color_Segment_CheckedPart)),Qt::SolidPattern);
    QPen penRed(brushRed,2.4f, Qt::SolidLine);

    painter->setBrush(Qt::BrushStyle::NoBrush);
    painter->setPen(penRed);
    painter->drawLine(left,y0,x,y0);



    focusColor = isEnable ?(isChecked ? 0xff424242:0xff646464) : Color_Font_Unable;
    if(isDeAct)  focusColor = Color_Text_Deactivate;

    QBrush brushRect(QColor(QRgba64::fromArgb32(focusColor)),Qt::SolidPattern);
    r = 2;
    yArrow =4;
    int nLeft,nTop,nRx = r<<1,nRy = yArrow<<1;
    nLeft = left - r;
    nTop = y0 - yArrow;
    painter->fillRect(nLeft,nTop,nRx,nRy,brushRect);


}


void AngleGridItem::drawPartSegmentSub(QPainter* painter,int x,int y, quint32 boolFlag)
{
    int left,right,r = 16,y0 = -1 + y;
    int xArrow = 5 +x,yArrow = 7 +y;
    DefineColorTxtR2();

    qreal thickness = 1.8f ;

    QBrush brushFill(QColor(QRgba64::fromArgb32(focusColor)),Qt::SolidPattern);
    QBrush brushBorder(QColor(QRgba64::fromArgb32(textColor)),Qt::SolidPattern);
    QPen pen(brushBorder,thickness, Qt::SolidLine);


    painter->setBrush(brushFill);
    painter->setPen(pen);
    drawSvgArrow(painter,xArrow,yArrow,boolFlag);
    left = x - r;
    right = x + r;

    painter->drawLine(left,y0,right,y0);


    QBrush brushRed(QColor(QRgba64::fromArgb32(Color_Segment_CheckedPart)),Qt::SolidPattern);
    QPen penRed(brushRed,2.4f, Qt::SolidLine);

    painter->setBrush(Qt::BrushStyle::NoBrush);
    painter->setPen(penRed);
    painter->drawLine(x,y0,right,y0);


    focusColor = isEnable ?(isChecked ? 0xff424242:0xff646464) : Color_Font_Unable;
    if(isDeAct)  focusColor = Color_Text_Deactivate;

    QBrush brushRect(QColor(QRgba64::fromArgb32(focusColor)),Qt::SolidPattern);
    r = 2;
    yArrow =4;
    int nLeft,nTop,nRx = r<<1,nRy = yArrow<<1;
    nLeft = right - r;
    nTop = y0 - yArrow;
    painter->fillRect(nLeft,nTop,nRx,nRy,brushRect);
}

void AngleGridItem::drawSvgArrow(QPainter* painter,int x,int y, quint32 boolFlag)
{

    int nSize=18,left,r,top;
    QSvgRenderer render;
    QString txt ("<svg t=\"1732794011009\" class=\"icon\" viewBox=\"0 0 1024 1024\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" p-id=\"21589\" width=\"200\" height=\"200\"><path d=\"M216.746667 836.266667V183.04a34.133333 34.133333 0 0 1 56.32-26.026667L794.88 597.333333a34.133333 34.133333 0 0 1-22.186667 60.16h-306.346666l-190.293334 202.24a34.133333 34.133333 0 0 1-59.306666-23.466666z\" p-id=\"21590\"></path></svg>");
    QByteArray contents= txt.toLocal8Bit();
    render.load(contents);
    // QSize size = render.defaultSize ();
    r = nSize>>1;
    left =  x - r;
    top = y - r;

    QRectF bounds(left,top,nSize,nSize);

    // painter->drawRect(bounds);
    render.render (painter,bounds);
}

}
}
